/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import dataRdb from '@ohos.data.rdb'
import { STORE_CONFIG } from './RdbConst';
import { LogBackEntity } from './LogBackEntity';

export class RdbModel {
    private rdbStore: any = null
    private tableName: string = ''
    private sqlCreateTable: string = ''
    private columns: Array<string> = []

    constructor(tableName: string, sqlCreateTable: string, columns: Array<string>) {
        this.tableName = tableName
        this.sqlCreateTable = sqlCreateTable
        this.columns = columns
    }

    getRdbStore(callback) {
        if (this.rdbStore != null) {
            callback()
            return;
        }
        dataRdb.getRdbStore(globalThis.context, STORE_CONFIG, 1, (err, rdb) => {
            this.rdbStore = rdb
            this.rdbStore.executeSql(this.sqlCreateTable)
            callback()
        })
    }

    insertData(entity: LogBackEntity, callback) {
        const valueBucket = {
            'level': entity.level,
            'msg': entity.msg,
        }
        setTimeout(() => {
            dataRdb.getRdbStore(globalThis.context, STORE_CONFIG, 1, (err, rdb) => {
                rdb.insert(this.tableName, valueBucket, function (err, ret) {
                    callback(ret)
                })
            })
        }, 5000)
    }

    query(predicates, callback) {
        let self = this
        dataRdb.getRdbStore(globalThis.context, STORE_CONFIG, 1, (err, rdb) => {
            rdb.query(predicates, this.columns, function (err, resultSet) {
                let resultList = self.getListFromResultSet(resultSet)
                callback(resultList)
            })
        })
    }

    getListFromResultSet(resultSet) {
        let studentList = []
        for (let i = 0;i < resultSet.rowCount; i++) {
            let entity = new LogBackEntity()
            entity.id = resultSet.getDouble(resultSet.getColumnIndex('id'))
            entity.level = resultSet.getString(resultSet.getColumnIndex('level'))
            entity.msg = resultSet.getString(resultSet.getColumnIndex('msg'))
            studentList.push(entity)
            resultSet.goToNextRow()
        }
        return studentList
    }
}